package com.sdy.resdir.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.common.model.BizException;
import com.sdy.common.model.Response;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.StringUtil;
import com.sdy.dcsb.api.DcsbApi;
import com.sdy.resdir.biz.mapper.RdSystemIpMapper;
import com.sdy.resdir.biz.model.*;
import com.sdy.resdir.biz.mapper.RdIpImpleOrderMapper;
import com.sdy.resdir.biz.param.IpImpleOrderParam;
import com.sdy.resdir.biz.service.*;
import com.sdy.mvc.service.impl.BaseServiceImpl;
import com.sdy.resdir.biz.vo.IpImpleOrderInfoVo;
import com.sdy.resdir.biz.vo.IpImpleOrderVo;
import com.sdy.usercenter.api.UserQueryApi;
import com.sdy.usercenter.api.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * ip实施工单 服务实现类
 * </p>
 *
 * @author cgj
 * @since 2019-12-17
 */
@Slf4j
@Service
public class RdIpImpleOrderServiceImpl extends BaseServiceImpl<RdIpImpleOrder> implements RdIpImpleOrderService {
    @Resource
    private RdIpImpleOrderMapper rdIpImpleOrderMapper;
    @Autowired
    private UserQueryApi userQueryApi;
    @Autowired
    private RdSelfBuiltSystemService appService;
    @Autowired
    private RdIpChangeService ipChangeService;
    @Autowired
    private RdResourceDirService dirService;
    @Autowired
    private DcsbApi dcsbApi;
    @Autowired
    private RdResDetailsApiService rdResDetailsApiService;
    @Autowired
    private RdSelfBuiltSystemService rdSelfBuiltSystemService;
    @Autowired
    private RdSystemIpService rdSystemIpService;
    @Resource
    private RdSystemIpMapper ipMapper;

    @Override
    public IPage<IpImpleOrderVo> ipImpleOrderPageList(Page page, String name, String ip, Integer state, Integer userId) {
        UserDTO user = userQueryApi.getUser(userId);
        name = StringUtil.isNotEmpty(name) && StringUtil.isNotBlank(name) ? name : null;
        ip = StringUtil.isNotEmpty(ip) && StringUtil.isNotBlank(ip) ? ip : null;
        IpImpleOrderParam param = new IpImpleOrderParam()
                .setSize(page.getSize())
                .setCurrent((page.getCurrent() - 1) * page.getSize())
                .setAppName(name)
                .setIp(ip)
                .setState(state)
                .setDeptId(user.getOwnDeptId());
        List<IpImpleOrderVo> ipImpleOrderVos = rdIpImpleOrderMapper.ipImpleOrderPageList(param);
        List<String> oldIpList = ipImpleOrderVos.stream().map(IpImpleOrderVo::getOldIP).collect(Collectors.toList());
        List<RdIpChange> ipChangeList = new ArrayList<>();
        if (!oldIpList.isEmpty()) {
            ipChangeList = ipChangeService.list(new LambdaQueryWrapper<RdIpChange>().in(RdIpChange::getOldIp, oldIpList));
        }
        if (ipImpleOrderVos != null && !ipImpleOrderVos.isEmpty()) {
            for (IpImpleOrderVo one : ipImpleOrderVos) {
                if (ipChangeList != null && !ipChangeList.isEmpty()) {
                    for (RdIpChange oneIpChange : ipChangeList) {
                        if (one.getOldIP() != null && StringUtil.isNotBlank(one.getOldIP()) && oneIpChange.getOldIp() != null && StringUtil.isNotBlank(oneIpChange.getOldIp()) && one.getOldIP().equals(oneIpChange.getOldIp())) {
                            one.setOldIP(one.getOldIP());
                        }
                    }
                }
                one.setUserName(userQueryApi.getUser(one.getUserId()).getName());
            }
        }

        int total = rdIpImpleOrderMapper.ipImpleOrderPageListTotal(param);
        IPage<IpImpleOrderVo> pageData = new Page<>();
        pageData.setRecords(ipImpleOrderVos).setSize(page.getSize()).setCurrent(page.getCurrent()).setTotal(total);
        return pageData;
    }

    @Override
    public IpImpleOrderInfoVo ipImpleOrderInfo(Integer orderId) {
        IpImpleOrderInfoVo orderInfoVo = new IpImpleOrderInfoVo();
        RdIpImpleOrder rdIpImpleOrder = rdIpImpleOrderMapper.selectOne(Wrappers.<RdIpImpleOrder>lambdaQuery().eq(RdIpImpleOrder::getId, orderId));
        // 查询自建系统信息,并放入Vo类
        RdSelfBuiltSystem app = appService.getOne(Wrappers.<RdSelfBuiltSystem>lambdaQuery().eq(RdSelfBuiltSystem::getId, rdIpImpleOrder.getAppId()));
        orderInfoVo.setId(orderId).setSysName(app.getSysName()).setSysCode(app.getSysCode()).setSysDesc(app.getSysDescribe());
        // 查询IP实施工单上面绑定的IP变动数据
        List<RdIpChange> ipChangeList = ipChangeService.list(Wrappers.<RdIpChange>lambdaQuery().in(RdIpChange::getId, rdIpImpleOrder.getIpId().split(",")));
        List<String> resIds = ipChangeList.stream().map(RdIpChange::getOldResIdList).collect(Collectors.toList());
        resIds.addAll(ipChangeList.stream().map(RdIpChange::getNewResIdList).collect(Collectors.toList()));
        String[] resIdList = String.join(",", resIds).split(",");
        List<RdResourceDir> resList = dirService.list(Wrappers.<RdResourceDir>lambdaQuery().in(RdResourceDir::getId, resIdList));
        // 根据资源id放入资源名称
        for (RdResourceDir dir : resList) {
            for (RdIpChange change : ipChangeList) {
                if (null != change.getOldResIdList() && change.getOldResIdList().contains(dir.getId() + "")) {
                    change.getOldResName().add(dir.getResName());
                    change.setOldResIdList(change.getOldResIdList().replace(dir.getId() + "", ""));
                }
                if (null != change.getNewResIdList() && change.getNewResIdList().contains(dir.getId() + "")) {
                    change.getNewResName().add(dir.getResName());
                    change.setNewResIdList(change.getNewResIdList().replace(dir.getId() + "", ""));
                }
            }
        }
        orderInfoVo.setIpChanges(ipChangeList);
        return orderInfoVo;
    }

    /**
     * Ip实施工单完成
     *
     * @param orderId
     * @return
     * @throws BizException
     */
    @Override
    public int impleOrderInfoDone(Integer orderId) throws BizException {
        // 查询实施工单详细信息
        RdIpImpleOrder rdIpImpleOrder = rdIpImpleOrderMapper.selectOne(Wrappers.<RdIpImpleOrder>lambdaQuery().eq(RdIpImpleOrder::getId, orderId));
        Assert.isNull(rdIpImpleOrder, "该实施工单不存在或无法获取该实施工单信息");
        Assert.isTrue(rdIpImpleOrder.getState() == 1, "该实施工单已实施完成,禁止重复操作");
        // 该订单的自建系统信息
        RdSelfBuiltSystem rdSelfBuiltSystem = rdSelfBuiltSystemService.getOne(new LambdaQueryWrapper<RdSelfBuiltSystem>()
                .eq(RdSelfBuiltSystem::getId, rdIpImpleOrder.getAppId()));
        Assert.isNull(rdSelfBuiltSystem, "该自建系统不存在");
        String name = getName(rdSelfBuiltSystem);
        // 实施工单相关ipchange的id
        String ipId = rdIpImpleOrder.getIpId();
        RdIpChange ipChange = ipChangeService.getById(ipId);
        if (ipChange != null) {
            String newIp = ipChange.getNewIp();
            String oldIp = ipChange.getOldIp();
            // ipChange新资源
            List<String> ipChangeNewResList = new ArrayList<>();
            if (StringUtil.isNotBlank(ipChange.getNewResIdList())) {
                String[] newResIds = ipChange.getNewResIdList().split(",");
                ipChangeNewResList = new ArrayList<>(Arrays.asList(newResIds));
            }
            // ipChange旧资源
            List<String> ipChangeOldResList = new ArrayList<>();
            if (StringUtil.isNotBlank(ipChange.getOldResIdList())) {
                String[] oldResArray = ipChange.getOldResIdList().split(",");
                ipChangeOldResList = new ArrayList<>(Arrays.asList(oldResArray));
            }
            // 删除
            if (rdIpImpleOrder.getType() == 2) {
                deleteTpeImpleOrder(ipChange, oldIp, ipChangeOldResList);
                // 编辑||新增
            } else {
                // 新绑定的资源
                List<String> addResIds = new ArrayList<>();
                // 取消绑定的资源
                List<String> oldResList = new ArrayList<>();
                RdSystemIp oldRdIp = rdSystemIpService.getOne(new LambdaQueryWrapper<RdSystemIp>().eq(RdSystemIp::getIp, oldIp).eq(RdSystemIp::getRelfSysId, ipChange.getAppId()));
                // 编辑
                if (ipChange.getType() == 1) {
                    updateTypeImpleOrder(rdSelfBuiltSystem, name, ipChange, addResIds, oldResList, newIp, oldIp, oldRdIp, ipChangeNewResList, ipChangeOldResList);
                    // 新增
                } else if (ipChange.getType() == 0) {
                    addTypeImpleOrder(rdSelfBuiltSystem, name, ipChange, newIp, ipChangeNewResList);
                }
            }
        }
        int updateIpImpleOrder = rdIpImpleOrderMapper.updateById(new RdIpImpleOrder().setId(orderId).setState(1));
        Assert.isTrue(updateIpImpleOrder == 0, "实施过程出现错误,请重试");
        return 1;
    }

    private void deleteTpeImpleOrder(RdIpChange ipChange, String oldIp, List<String> ipChangeOldResList) throws BizException {
        // 要删除的rdSystemIp
        RdSystemIp rdIp = rdSystemIpService.getOne(new LambdaQueryWrapper<RdSystemIp>().eq(RdSystemIp::getIp, oldIp).eq(RdSystemIp::getRelfSysId, ipChange.getAppId()));
        if (rdIp != null) {
            boolean deleteRdIp = rdSystemIpService.removeById(rdIp.getId());
            Assert.notTrue(deleteRdIp, "删除资源失败");
        }
        if (!ipChangeOldResList.isEmpty() && oldIp != null) {
            List<RdResDetailsApi> details = rdResDetailsApiService.list(new LambdaQueryWrapper<RdResDetailsApi>()
                    .in(RdResDetailsApi::getResDirId, ipChangeOldResList));
            List<String> ipList = new ArrayList<>();
            ipList.add(oldIp);
            List<String> addresses = details.stream().map(RdResDetailsApi::getApiAddress).collect(Collectors.toList());
            if (!addresses.isEmpty()) {
                Response response = dcsbApi.cancelInterfaceServiceAuthority(addresses, ipList.toArray(new String[ipList.size()]));
                Assert.isTrue(!response.getSuccess(), "ip删除权限失败");
            }
        }
    }

    private void addTypeImpleOrder(RdSelfBuiltSystem rdSelfBuiltSystem, String name, RdIpChange ipChange, String newIp, List<String> ipChangeNewResList) throws BizException {
        boolean save = rdSystemIpService.save(new RdSystemIp()
                .setRelfSysId(ipChange.getAppId())
                .setIp(newIp)
                .setCreateTime(new Date())
                .setResIdList(ipChange.getNewResIdList()));
        Assert.notTrue(save, "保存资源失败");
        if (newIp != null && !ipChangeNewResList.isEmpty()) {
            List<RdResDetailsApi> details = rdResDetailsApiService.list(new LambdaQueryWrapper<RdResDetailsApi>()
                    .in(RdResDetailsApi::getResDirId, ipChangeNewResList));
            List<String> addresses = details.stream().map(RdResDetailsApi::getApiAddress).collect(Collectors.toList());
            List<String> ipList = new ArrayList<>();
            ipList.add(newIp);
            if (!addresses.isEmpty()) {
                Response response = dcsbApi.openInterfaceServiceAuthority(addresses, name, rdSelfBuiltSystem.getSysName(), ipList.toArray(new String[ipList.size()]));
                Assert.isTrue(!response.getSuccess(), "ip赋值权限失败");
            }
        }
    }

    private void updateTypeImpleOrder(RdSelfBuiltSystem rdSelfBuiltSystem, String name, RdIpChange ipChange, List<String> addResIds, List<String> oldResList, String newIp, String oldIp, RdSystemIp oldRdIp, List<String> ipChangeNewResList, List<String> ipChangeOldResList) throws BizException {
        // 新增的资源
        getNewResOrDeleteRes(addResIds, ipChangeNewResList, ipChangeOldResList);
        // 取消绑定的资源
        getNewResOrDeleteRes(oldResList, ipChangeOldResList, ipChangeNewResList);
        // 当前ip原先绑定的资源
        List<String> resIdList = new ArrayList<>();
        if (oldRdIp != null && StringUtil.isNotBlank(oldRdIp.getResIdList())) {
            resIdList = new ArrayList<>(Arrays.asList(oldRdIp.getResIdList().split(",")));
        }
        if (oldIp != null && newIp != null) {
            // ip不变，只变资源
            if (oldIp.equals(newIp)) {
                IpNotChangeResChangeOrder(rdSelfBuiltSystem, name, ipChange, addResIds, oldResList, oldRdIp, ipChangeNewResList, ipChangeOldResList, resIdList);
                //ip修改了
            } else {
                // 同个ip，多个实施工单
                RdSystemIp oldOne = rdSystemIpService.getOne(new LambdaQueryWrapper<RdSystemIp>().eq(RdSystemIp::getIp, ipChange.getOldIp()).eq(RdSystemIp::getRelfSysId, ipChange.getAppId()));
                RdSystemIp newOne = rdSystemIpService.getOne(new LambdaQueryWrapper<RdSystemIp>().eq(RdSystemIp::getIp, ipChange.getNewIp()).eq(RdSystemIp::getRelfSysId, ipChange.getAppId()));
                // 第一次修改ip
                if (oldOne != null && newOne == null) {
                    boolean updateRdSystemIp = rdSystemIpService.update(new LambdaUpdateWrapper<RdSystemIp>()
                            .eq(RdSystemIp::getIp, ipChange.getOldIp())
                            .eq(RdSystemIp::getRelfSysId, ipChange.getAppId())
                            .set(RdSystemIp::getIp, ipChange.getNewIp())
                            .set(RdSystemIp::getResIdList, ipChange.getNewResIdList()));
                    Assert.notTrue(updateRdSystemIp, "更改资源列表失败");
                    // 第二次及之后的修改
                } else if (oldOne == null && newOne != null) {
                    OneMoreOrderDone(ipChange.getAppId(), ipChangeNewResList, newIp, newOne);
                }
                // 新的ip绑定新的资源
                if (!ipChangeNewResList.isEmpty()) {
                    ipChangeNewIpAddNewRes(rdSelfBuiltSystem, name, newIp, ipChangeNewResList);
                }
                // 旧的ip删除权限
                if (!ipChangeOldResList.isEmpty()) {
                    ipChangeOldIpDeleteRes(oldIp, ipChangeOldResList);
                }
            }
        }
    }

    private void OneMoreOrderDone(Integer appId, List<String> ipChangeNewResList, String newIp, RdSystemIp newOne) throws BizException {
        // 修改之后已存在的资源
        String newRdIpResIdString = newOne.getResIdList();
        // 获取新ip已绑定的资源列表
        String[] newRdIpResIdArray = null;
        List<String> newRdIpResIdList = new ArrayList<>();
        // 如果新ip已绑定资源不为空，转换成list
        if (StringUtil.isNotBlank(newRdIpResIdString)) {
            newRdIpResIdArray = newRdIpResIdString.split(",");
            newRdIpResIdList = new ArrayList<>(Arrays.asList(newRdIpResIdArray));
        }
        // 如果新增资源还未存在，则新增，返回新资源加原有资源的总和
        if (!ipChangeNewResList.isEmpty() && !newRdIpResIdList.isEmpty()) {
            for (String oneRes : ipChangeNewResList) {
                if (!newRdIpResIdList.contains(oneRes)) {
                    newRdIpResIdList.add(oneRes);
                }
            }
        } else if (!ipChangeNewResList.isEmpty()) {
            newRdIpResIdList.addAll(ipChangeNewResList);
        }
        // 如果资源总和不为空，转换成String
        if (!newRdIpResIdList.isEmpty()) {
            newRdIpResIdString = StringUtil.join(newRdIpResIdList, ",");
        }
        // 更新该ip绑定资源
        boolean updateRdSystemIp = rdSystemIpService.update(new LambdaUpdateWrapper<RdSystemIp>()
                .eq(RdSystemIp::getIp, newOne.getIp())
                .eq(RdSystemIp::getRelfSysId, appId)
                .set(RdSystemIp::getIp, newIp)
                .set(RdSystemIp::getResIdList, newRdIpResIdString));
        Assert.notTrue(updateRdSystemIp, "更改资源列表失败");
    }

    private void IpNotChangeResChangeOrder(RdSelfBuiltSystem rdSelfBuiltSystem, String name, RdIpChange ipChange, List<String> addResIds, List<String> oldResList, RdSystemIp oldRdIp, List<String> newResIdList, List<String> oldResIdList, List<String> resIdList) throws BizException {
        // 取消了资源绑定
        if (newResIdList.isEmpty() && !oldResIdList.isEmpty()) {
            if (!resIdList.isEmpty()) {
                resIdList.removeAll(oldResList);
            }
            updateRdSystemIp(ipChange, resIdList);
            // 新加资源
        } else if (!newResIdList.isEmpty() && oldResIdList.isEmpty()) {
            resIdList.addAll(addResIds);
            updateRdSystemIp(ipChange, resIdList);
            // 新加同时删除
        } else if (!newResIdList.isEmpty() && !oldResIdList.isEmpty()) {
            if (!addResIds.isEmpty()) {
                resIdList.addAll(addResIds);
            }
            if (!resIdList.isEmpty()) {
                resIdList.removeAll(oldResList);
            }
            updateRdSystemIp(ipChange, resIdList);
        }
        ipNotChange(rdSelfBuiltSystem, name, addResIds, oldResList, ipChange.getNewIp());
    }

//    private void deleteTypeOrderCancelAuthority(RdIpChange rdIpChange) throws BizException {
//        // 要删除的iplist
//        String oldIp = rdIpChange.getOldIp();
//        RdSystemIp rdIp = rdSystemIpService.getOne(new LambdaQueryWrapper<RdSystemIp>().eq(RdSystemIp::getIp, oldIp));
//        boolean deleteRdIp = rdSystemIpService.removeById(rdIp.getId());
//        Assert.notTrue(deleteRdIp, "删除资源失败");
//        if (StringUtil.isNotBlank(rdIpChange.getOldResIdList()) && oldIp != null) {
//            String[] oldResIds = rdIpChange.getOldResIdList().split(",");
//            List<String> oldResIdList = new ArrayList<>(Arrays.asList(oldResIds));
//            List<RdResDetailsApi> details = rdResDetailsApiService.list(new LambdaQueryWrapper<RdResDetailsApi>()
//                    .in(RdResDetailsApi::getResDirId, oldResIdList));
//            List<String> ipList = new ArrayList<>();
//            ipList.add(oldIp);
//            List<String> addresses = details.stream().map(RdResDetailsApi::getApiAddress).collect(Collectors.toList());
//            if (!addresses.isEmpty()) {
//                Response response = dcsbApi.cancelInterfaceServiceAuthority(addresses, ipList.toArray(new String[ipList.size()]));
//                Assert.isTrue(!response.getSuccess(), "ip删除权限失败");
//            }
//        }
//    }

    private void updateRdSystemIp(RdIpChange ipChange, List<String> split) throws BizException {
        String nowResString = StringUtil.join(split, ",");
        boolean updateRdSystemIp = rdSystemIpService.update(new LambdaUpdateWrapper<RdSystemIp>()
                .eq(RdSystemIp::getIp, ipChange.getOldIp())
                .eq(RdSystemIp::getRelfSysId, ipChange.getAppId())
                .set(RdSystemIp::getIp, ipChange.getOldIp())
                .set(RdSystemIp::getResIdList, nowResString));
        Assert.notTrue(updateRdSystemIp, "更改资源列表失败");
    }

//    /**
//     * ip新增资源
//     *
//     * @param rdSelfBuiltSystem
//     * @param name
//     * @param newIp
//     * @throws BizException
//     */
//    private void ipAddRes(RdSelfBuiltSystem rdSelfBuiltSystem, String name, List<String> ipChangeNewResList, String newIp) throws BizException {
//        if (newIp != null && !ipChangeNewResList.isEmpty()) {
//            List<RdResDetailsApi> details = rdResDetailsApiService.list(new LambdaQueryWrapper<RdResDetailsApi>()
//                    .in(RdResDetailsApi::getResDirId, ipChangeNewResList));
//            List<String> addresses = details.stream().map(RdResDetailsApi::getApiAddress).collect(Collectors.toList());
//            List<String> ipList = new ArrayList<>();
//            ipList.add(newIp);
//            if (!addresses.isEmpty()) {
//                Response response = dcsbApi.openInterfaceServiceAuthority(addresses, name, rdSelfBuiltSystem.getSysName(), ipList.toArray(new String[ipList.size()]));
//                Assert.isTrue(!response.getSuccess(), "ip赋值权限失败");
//            }
//        }
//    }

    /**
     * ip变动，且删除资源绑定
     *
     * @param ipChangeOldResList
     * @param oldIp
     * @param ipChangeOldResList
     * @return
     * @throws BizException
     */
    private void ipChangeOldIpDeleteRes(String oldIp, List<String> ipChangeOldResList) throws BizException {
        List<RdResDetailsApi> deleteDetails = rdResDetailsApiService.list(new LambdaQueryWrapper<RdResDetailsApi>()
                .in(RdResDetailsApi::getResDirId, ipChangeOldResList));
        List<String> deleteAddresses = deleteDetails.stream().map(RdResDetailsApi::getApiAddress).collect(Collectors.toList());
        List<String> oldIpList = new ArrayList<>();
        oldIpList.add(oldIp);
        if (!deleteAddresses.isEmpty()) {
            Response cancelResponse = dcsbApi.cancelInterfaceServiceAuthority(deleteAddresses, oldIpList.toArray(new String[oldIpList.size()]));
            Assert.isTrue(!cancelResponse.getSuccess(), "ip删除权限失败");
        }
    }

    /**
     * ip变动，绑定新资源
     *
     * @param rdSelfBuiltSystem
     * @param name
     * @param newIp
     * @param ipChangeNewResList
     * @return
     * @throws BizException
     */
    private void ipChangeNewIpAddNewRes(RdSelfBuiltSystem rdSelfBuiltSystem, String name, String newIp, List<String> ipChangeNewResList) throws BizException {
        List<RdResDetailsApi> details = rdResDetailsApiService.list(new LambdaQueryWrapper<RdResDetailsApi>()
                .in(RdResDetailsApi::getResDirId, ipChangeNewResList));
        // 获取资源的接口地址
        List<String> addresses = details.stream().map(RdResDetailsApi::getApiAddress).collect(Collectors.toList());
        List<String> ipList = new ArrayList<>();
        ipList.add(newIp);
        // 如果接口地址不为空，则给新ip绑定资源
        if (!addresses.isEmpty()) {
            Response response = dcsbApi.openInterfaceServiceAuthority(addresses, name, rdSelfBuiltSystem.getSysName(), ipList.toArray(new String[ipList.size()]));
            Assert.isTrue(!response.getSuccess(), "ip赋权限失败");
        }
    }

    /**
     * ip不变的情况下，资源的变动
     *
     * @param rdSelfBuiltSystem
     * @param name
     * @param addResIds
     * @param oldResList
     * @param newIp
     * @throws BizException
     */
    private void ipNotChange(RdSelfBuiltSystem rdSelfBuiltSystem, String name, List<String> addResIds, List<String> oldResList, String newIp) throws BizException {
        List<String> ipList = new ArrayList<>();
        ipList.add(newIp);
        // 新绑定资源不为空，赋权限
        if (!addResIds.isEmpty()) {
            List<RdResDetailsApi> details = rdResDetailsApiService.list(new LambdaQueryWrapper<RdResDetailsApi>()
                    .in(RdResDetailsApi::getResDirId, addResIds));
            List<String> addresses = details.stream().map(RdResDetailsApi::getApiAddress).collect(Collectors.toList());
            if (!addresses.isEmpty()) {
                Response response = dcsbApi.openInterfaceServiceAuthority(addresses, name, rdSelfBuiltSystem.getSysName(), ipList.toArray(new String[ipList.size()]));
                Assert.isTrue(!response.getSuccess(), "ip赋权限失败");
            }
        }
        // 取消绑定的资源不为空，取消权限
        if (!oldResList.isEmpty()) {
            List<RdResDetailsApi> details = rdResDetailsApiService.list(new LambdaQueryWrapper<RdResDetailsApi>()
                    .in(RdResDetailsApi::getResDirId, oldResList));
            List<String> addresses = details.stream().map(RdResDetailsApi::getApiAddress).collect(Collectors.toList());
            if (!addresses.isEmpty()) {
                Response response = dcsbApi.cancelInterfaceServiceAuthority(addresses, ipList.toArray(new String[ipList.size()]));
                Assert.isTrue(!response.getSuccess(), "ip删除权限失败");
            }
        }
    }

//    /**
//     * 如果是删除类型的实施工单直接删除即可
//     *
//     * @param rdIpImpleOrder
//     * @param addIps
//     * @param updateIps
//     * @param oldIps
//     * @throws BizException
//     */
//    private void deleteOrder(RdIpImpleOrder rdIpImpleOrder, List<RdSystemIp> addIps, List<RdSystemIp> updateIps, List<RdSystemIp> oldIps) throws BizException {
//        if (rdIpImpleOrder.getType() != 2) {
//            String[] ipChangeId = rdIpImpleOrder.getIpId().split(",");
//            List<RdIpChange> ipChanges = ipChangeService.list(Wrappers.<RdIpChange>lambdaQuery().in(RdIpChange::getId, ipChangeId));
//            RdSystemIp rdSystemIp = rdSystemIpService.getOne(new LambdaQueryWrapper<RdSystemIp>().eq(RdSystemIp::getId, ipChanges.get(0).getAimsId()));
//            String oldResIdIpList = "";
//            if (rdSystemIp != null) {
//                oldResIdIpList = rdSystemIp.getResIdList();
//            }
//            for (RdIpChange ipChange : ipChanges) {
//                Date now = new Date();
//                // 新增
//                if (ipChange.getType() == 0) {
//                    RdSystemIp ip = new RdSystemIp()
//                            .setRelfSysId(ipChange.getAppId())
//                            .setCreateTime(now)
//                            .setIp(ipChange.getNewIp())
//                            .setResIdList(ipChange.getNewResIdList());
//                    addIps.add(ip);
//                }
//                // 修改
//                if (ipChange.getType() == 1) {
//                    List<String> nowResIdList = new ArrayList<>();
//                    if (StringUtil.isNotBlank(ipChange.getNewResIdList()) && StringUtil.isNotBlank(oldResIdIpList)) {
//                        List<String> newResList = new ArrayList(Arrays.asList(ipChange.getNewResIdList().split(",")));
//                        List<String> oldResList = new ArrayList(Arrays.asList(oldResIdIpList.split(",")));
//                        nowResIdList.addAll(oldResList);
//                        for (String newRes : newResList) {
//                            if (!oldResList.contains(newRes)) {
//                                nowResIdList.add(newRes);
//                            }
//                        }
//                    }
//                    // 新的ip列表
//                    String resIdListString = StringUtils.join(nowResIdList.toArray(), ",");
//                    RdSystemIp ip = new RdSystemIp()
//                            .setId(ipChange.getAimsId())
//                            .setRelfSysId(ipChange.getAppId())
//                            .setCreateTime(now)
//                            .setIp(ipChange.getNewIp())
//                            .setResIdList(resIdListString);
//                    updateIps.add(ip);
//                    // 旧的ip列表
//                    RdSystemIp oldIp = new RdSystemIp()
//                            .setId(ipChange.getAimsId())
//                            .setRelfSysId(ipChange.getAppId())
//                            .setCreateTime(now)
//                            .setIp(ipChange.getOldIp())
//                            .setResIdList(ipChange.getOldResIdList());
//                    oldIps.add(oldIp);
//                }
//            }
//            if (!addIps.isEmpty()) {
//                List<RdSystemIp> delIps = new ArrayList<>();
//                for (RdSystemIp rd : addIps) {
//                    String newResIds = rd.getResIdList();
//                    // 旧的ip绑定单
//                    RdSystemIp one = rdSystemIpService.getOne(new LambdaQueryWrapper<RdSystemIp>().eq(RdSystemIp::getIp, rd.getIp())
//                            .eq(RdSystemIp::getRelfSysId, rd.getRelfSysId()));
//                    // 如果是新增资源
//                    if (one != null) {
//                        // 旧的资源
//                        String resIdList = one.getResIdList();
//                        delIps.add(one);
//                        if (StringUtil.isNotBlank(resIdList) && StringUtil.isNotBlank(rd.getResIdList())) {
//                            for (String newResId : rd.getResIdList().split(",")) {
//                                List<String> oldResIdList = new ArrayList<>(Arrays.asList(resIdList.split(",")));
//                                if (!oldResIdList.contains(newResId)) {
//                                    oldResIdList.add(newResId);
//                                    oldResIdList.stream().distinct().collect(Collectors.toList());
//                                    resIdList = resIdList + "," + newResId;
//                                }
//                            }
//                            rd.setResIdList(resIdList);
//                        }
//                        // 如果是修改资源
//                    } else {
//                        rd.setResIdList(newResIds);
//                    }
//                }
//                List<Integer> delIds = delIps.stream().map(RdSystemIp::getId).collect(Collectors.toList());
//                // 如果新增的数据自建系统id，ip有重复，则把原有数据删除，新增一条
//                if (!delIds.isEmpty()) {
//                    int delOldOrder = ipMapper.deleteBatchIds(delIds);
//                    Assert.isTrue(delOldOrder == 0, "实施过程出现错误,请重试");
//
//                }
//                int addIpState = ipMapper.batchInsert(addIps);
//                Assert.isTrue(addIpState == 0, "实施过程出现错误,请重试");
//            }
//            if (!updateIps.isEmpty()) {
//                int updateIpState = ipMapper.batchUpdate(updateIps);
//                Assert.isTrue(updateIpState == 0, "实施过程出现错误,请重试");
//            }
//
//        }
//    }


    /**
     * 得到新绑定资源或取消绑定的资源
     *
     * @param addResIds
     * @param newResIds
     * @param oldResIds
     */
    private void getNewResOrDeleteRes(List<String> addResIds, List<String> newResIds, List<String> oldResIds) {
        if (!newResIds.isEmpty()) {
            // 新绑定资源
            for (String resId : newResIds) {
                if (!oldResIds.isEmpty() && !addResIds.contains(resId) && !oldResIds.contains(resId)) {
                    addResIds.add(resId);
                }
                if (oldResIds.isEmpty()) {
                    addResIds.add(resId);
                }
            }

        }
    }


//    /**
//     * 取消ip权限赋值
//     *
//     * @param rd
//     * @param oldIp
//     * @throws BizException
//     */
//    private void cancelAuthority(RdIpChange rd, String oldIp) throws BizException {
//        String[] oldResIds = rd.getOldResIdList().split(",");
//        List<String> oldResIdList=new ArrayList<>(Arrays.asList(oldResIds));
//        List<RdResDetailsApi> details = rdResDetailsApiService.list(new LambdaQueryWrapper<RdResDetailsApi>()
//                .in(RdResDetailsApi::getResDirId, oldResIdList));
//        List<String> ipList = new ArrayList<>();
//        ipList.add(oldIp);
//        List<String> addresses = details.stream().map(RdResDetailsApi::getApiAddress).collect(Collectors.toList());
//        if (!addresses.isEmpty()) {
//            Response response = dcsbApi.cancelInterfaceServiceAuthority(addresses, ipList.toArray(new String[ipList.size()]));
//            Assert.isTrue(!response.getSuccess(), "ip删除权限失败");
//        }
//    }

    @Override
    public String getName(RdSelfBuiltSystem rd) {
        String code = userQueryApi.getDept(rd.getDeptId()).getCode();
        int length = code.length();
        String name = null;
        if (length == 3) {
            name = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code).getName()) ? userQueryApi.getDeptByCode(code).getName() : userQueryApi.getDeptByCode(code).getAbbreviation();

        } else if (length == 6) {
            String name1 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 3)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 3)).getName() : userQueryApi.getDeptByCode(code.substring(0, 3)).getAbbreviation();
            String name2 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code).getName()) ? userQueryApi.getDeptByCode(code).getName() : userQueryApi.getDeptByCode(code).getAbbreviation();
            name = name1 + "/" + name2;
        } else if (length == 9) {
            String name1 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 3)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 3)).getName() : userQueryApi.getDeptByCode(code.substring(0, 3)).getAbbreviation();
            String name2 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 6)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 6)).getName() : userQueryApi.getDeptByCode(code.substring(0, 6)).getAbbreviation();
            String name3 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code).getName()) ? userQueryApi.getDeptByCode(code).getName() : userQueryApi.getDeptByCode(code).getAbbreviation();
            name = name1 + "/" + name2 + "/" + name3;
        } else if (length == 12) {
            String name1 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 3)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 3)).getName() : userQueryApi.getDeptByCode(code.substring(0, 3)).getAbbreviation();
            String name2 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 6)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 6)).getName() : userQueryApi.getDeptByCode(code.substring(0, 6)).getAbbreviation();
            String name3 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 9)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 9)).getName() : userQueryApi.getDeptByCode(code.substring(0, 9)).getAbbreviation();
            String name4 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code).getName()) ? userQueryApi.getDeptByCode(code).getName() : userQueryApi.getDeptByCode(code).getAbbreviation();
            name = name1 + "/" + name2 + "/" + name3 + "/" + name4;
        } else if (length == 15) {
            String name1 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 3)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 3)).getName() : userQueryApi.getDeptByCode(code.substring(0, 3)).getAbbreviation();
            String name2 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 6)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 6)).getName() : userQueryApi.getDeptByCode(code.substring(0, 6)).getAbbreviation();
            String name3 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 9)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 9)).getName() : userQueryApi.getDeptByCode(code.substring(0, 9)).getAbbreviation();
            String name4 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 12)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 12)).getName() : userQueryApi.getDeptByCode(code.substring(0, 12)).getAbbreviation();
            String name5 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code).getName()) ? userQueryApi.getDeptByCode(code).getName() : userQueryApi.getDeptByCode(code).getAbbreviation();
            name = name1 + "/" + name2 + "/" + name3 + "/" + name4 + '/' + name5;
        } else if (length == 18) {
            String name1 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 3)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 3)).getName() : userQueryApi.getDeptByCode(code.substring(0, 3)).getAbbreviation();
            String name2 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 6)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 6)).getName() : userQueryApi.getDeptByCode(code.substring(0, 6)).getAbbreviation();
            String name3 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 9)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 9)).getName() : userQueryApi.getDeptByCode(code.substring(0, 9)).getAbbreviation();
            String name4 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 12)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 12)).getName() : userQueryApi.getDeptByCode(code.substring(0, 12)).getAbbreviation();
            String name5 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 15)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 15)).getName() : userQueryApi.getDeptByCode(code.substring(0, 15)).getAbbreviation();
            String name6 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code).getName()) ? userQueryApi.getDeptByCode(code).getName() : userQueryApi.getDeptByCode(code).getAbbreviation();
            name = name1 + "/" + name2 + "/" + name3 + "/" + name4 + '/' + name5 + "/" + name6;
        } else if (length == 21) {
            String name1 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 3)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 3)).getName() : userQueryApi.getDeptByCode(code.substring(0, 3)).getAbbreviation();
            String name2 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 6)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 6)).getName() : userQueryApi.getDeptByCode(code.substring(0, 6)).getAbbreviation();
            String name3 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 9)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 9)).getName() : userQueryApi.getDeptByCode(code.substring(0, 9)).getAbbreviation();
            String name4 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 12)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 12)).getName() : userQueryApi.getDeptByCode(code.substring(0, 12)).getAbbreviation();
            String name5 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 15)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 15)).getName() : userQueryApi.getDeptByCode(code.substring(0, 15)).getAbbreviation();
            String name6 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 18)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 18)).getName() : userQueryApi.getDeptByCode(code.substring(0, 18)).getAbbreviation();
            String name7 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code).getName()) ? userQueryApi.getDeptByCode(code).getName() : userQueryApi.getDeptByCode(code).getAbbreviation();
            name = name1 + "/" + name2 + "/" + name3 + "/" + name4 + '/' + name5 + "/" + name6 + "/" + name7;
        } else if (length == 24) {
            String name1 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 3)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 3)).getName() : userQueryApi.getDeptByCode(code.substring(0, 3)).getAbbreviation();
            String name2 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 6)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 6)).getName() : userQueryApi.getDeptByCode(code.substring(0, 6)).getAbbreviation();
            String name3 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 9)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 9)).getName() : userQueryApi.getDeptByCode(code.substring(0, 9)).getAbbreviation();
            String name4 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 12)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 12)).getName() : userQueryApi.getDeptByCode(code.substring(0, 12)).getAbbreviation();
            String name5 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 15)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 15)).getName() : userQueryApi.getDeptByCode(code.substring(0, 15)).getAbbreviation();
            String name6 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 18)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 18)).getName() : userQueryApi.getDeptByCode(code.substring(0, 18)).getAbbreviation();
            String name7 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code.substring(0, 21)).getName()) ? userQueryApi.getDeptByCode(code.substring(0, 21)).getName() : userQueryApi.getDeptByCode(code.substring(0, 21)).getAbbreviation();
            String name8 = StringUtil.isNotBlank(userQueryApi.getDeptByCode(code).getName()) ? userQueryApi.getDeptByCode(code).getName() : userQueryApi.getDeptByCode(code).getAbbreviation();
            name = name1 + "/" + name2 + "/" + name3 + "/" + name4 + '/' + name5 + "/" + name6 + "/" + name7 + "/" + name8;
        }
        return name;
    }

    @Override
    public Integer insertBatch(List<RdIpImpleOrder> orderList) {
        return rdIpImpleOrderMapper.batchInsert(orderList);
    }
}
